import {
  Entity,
  Column,
  Tree,
  TreeChildren,
  TreeParent,
  ManyToMany,
  PrimaryColumn,
  BeforeInsert,
  BeforeUpdate,
} from 'typeorm';
import { v4 as uuidv4 } from 'uuid';
import * as moment from 'moment';
import { RoleEntity } from '../../role/entities/role.entity';

@Entity({ name: 'access' })
@Tree('closure-table')
export class AccessEntity {
  @PrimaryColumn()
  id: string = uuidv4();

  @Column({ type: 'varchar', nullable: true, length: 30, comment: '模块' })
  module_name: string;

  @Column({
    type: 'varchar',
    nullable: true,
    length: 30,
    comment: '操作',
  })
  action_name: string;

  @Column({ type: 'tinyint', comment: '类型：1:模块，2：菜单，3：操作' })
  type: number;

  @Column({ type: 'text', nullable: true, comment: '操作地址' })
  url: string;

  @Column({ type: 'tinyint', comment: '排序', default: 0 })
  sort: number;

  // onDelete: 'SET NULL'
  @TreeParent({ onDelete: 'CASCADE' })
  parent: AccessEntity;

  @TreeChildren({ cascade: true })
  children: AccessEntity[];

  @ManyToMany(() => RoleEntity, (role) => role.access)
  roles: RoleEntity[];

  @Column({ type: 'varchar', nullable: true })
  created_at: string;

  @Column({ type: 'varchar', nullable: true })
  updated_at: string;

  @BeforeInsert()
  createDates() {
    this.created_at = moment().format('YYYY-MM-DD HH:mm:ss');
  }

  @BeforeUpdate()
  updateDates() {
    this.updated_at = moment().format('YYYY-MM-DD HH:mm:ss');
  }
}
